/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import { getPermissionApi, getPermByUseridApi } from '@/api/comdesk/perm'
import { findpermbyusercode } from '@/api/role'
import { asyncRoutes, constantRoutes, resetRouter } from '@/router'
import { useUserStore } from '@/store/modules/user'
import { convertRouter, filterRoutes, perfectRouter } from '@/utils/routes'
import { localStorageConfig } from '@/config/localstorage.config.js'

export const useRoutesStore = defineStore('routes', {
  state: () => ({
    /**
     * 一级菜单值
     */
    tab: {
      data: undefined,
    },
    /**
     * 一级菜单
     */
    tabMenu: undefined,
    /**
     * 自定义激活菜单
     */
    activeMenu: {
      data: undefined,
    },
    /**
     * 一级菜单
     */
    routes: [],
  }),
  getters: {
    getTab: (state) => state.tab,
    getTabMenu: (state) =>
      state.tab.data
        ? state.routes.find((route) => route.name === state.tab.data)
        : { meta: { title: '' } },
    getActiveMenu: (state) => state.activeMenu,
    getRoutes: (state) =>
      state.routes.filter(
        (_route) => _route.meta && _route.meta.hidden !== true
      ),
    getPartialRoutes: (state) =>
      state.tab.data
        ? state.routes.find((route) => route.name === state.tab.data) &&
          state.routes.find((route) => route.name === state.tab.data).children
        : [],
  },
  actions: {
    clearRoutes() {
      this.routes = []
    },
    /**
     * @description 多模式设置路由
     * @param mode
     * @returns
     */
    async setRoutes() {
      const { getUserInfo } = useUserStore()
      const _userInfo = getUserInfo()
      // 默认前端路由
      let routes = [...asyncRoutes]
      const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
      _userInfo['pkCorp'] = pkCorp
      const res = await getPermByUseridApi(_userInfo).catch((error) =>
        console.log('getPermByUseridApi', getPermByUseridApi)
      )
      const pRes = await getPermissionApi(_userInfo)
      let userPerm = []
      let permRoutes = []
      if (res && res.code === 2000) {
        userPerm = res.data
      }
      if (pRes && pRes.code === 2000) {
        permRoutes = pRes.data
      }

      const _routers = perfectRouter(permRoutes, userPerm, true)
      if (_routers[_routers.length - 1].path !== '*')
        _routers.push({
          path: '/:pathMatch(.*)*',
          redirect: '/404',
          name: 'NotFound',
          meta: { hidden: true },
        })
      routes = convertRouter(_routers)

      // 根据权限和rolesControl过滤路由
      const accessRoutes = filterRoutes([...constantRoutes, ...routes])
      // accessRoutes.forEach((route) => {
      //   if(route)
      // })
      // 设置菜单所需路由
      this.routes = JSON.parse(JSON.stringify(accessRoutes))
      // 根据可访问路由重置Vue Router
      await resetRouter(accessRoutes)
    },
    changeMenuMeta(options) {
      function handleRoutes(routes) {
        return routes.map((route) => {
          if (route.name === options.name)
            Object.assign(route.meta, options.meta)
          if (route.children && route.children.length)
            route.children = handleRoutes(route.children)
          return route
        })
      }
      this.routes = handleRoutes(this.routes)
    },
    /**
     * @description 修改 activeName
     * @param activeMenu 当前激活菜单
     */
    changeActiveMenu(activeMenu) {
      this.activeMenu.data = activeMenu
    },
  },
})
